package com.example.servlet;

import com.example.*;
import com.example.dao.BookDao;
import com.example.dao.imol.BookDaoImpl;
import com.example.entity.Book;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/BookServlet")
public class BookServlet extends HttpServlet {
    private BookDao bookDao = new BookDaoImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String action = request.getParameter("action");
        if ("add".equals(action)) {
            String bookId = request.getParameter("bookId");
            String bookName = request.getParameter("bookName");
            String author = request.getParameter("author");
            String publisher = request.getParameter("publisher");
            int publicationYear = Integer.parseInt(request.getParameter("publicationYear"));
            double price = Double.parseDouble(request.getParameter("price"));
            int stockQuantity = Integer.parseInt(request.getParameter("stockQuantity"));
            Book book = new Book(bookId, bookName, author, publisher, publicationYear, price, stockQuantity);
            bookDao.addBook(book);
            PrintWriter out = response.getWriter();
            out.print("图书添加成功！");
            out.flush();
        } else if ("update".equals(action)) {
            // 处理图书更新逻辑，类似添加，先获取参数构建 Book 对象，再调用 bookDao.updateBook 方法
        } else if ("delete".equals(action)) {
            String bookId = request.getParameter("bookId");
            bookDao.deleteBook(bookId);
            PrintWriter out = response.getWriter();
            out.print("图书删除成功！");
            out.flush();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        String keyword = request.getParameter("keyword");
<<<<<<< HEAD
        System.out.println(keyword);
=======
>>>>>>> b820b4c53617dce5ceda1c53c8071e1b57d2805e
        List<Book> bookList = bookDao.getBooks(keyword);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(bookList);
        PrintWriter out = response.getWriter();
        out.print(json);
        out.flush();
    }
<<<<<<< HEAD

=======
>>>>>>> b820b4c53617dce5ceda1c53c8071e1b57d2805e
}